<?php
namespace app\mall\service;
/**
 * 订单操作
 */
class OrderService extends \app\base\service\BaseService {

    private $model = 'mall/MallOrder';

    /**
     * 添加购物车
     * @param $userId
     * @param $data
     * @return bool
     */
    public function addCart($userId, $data) {
        $qty = intval($data['qty']) ? intval($data['qty']) : 1;

        if (empty($data['pro_id']) && empty($data['mall_id'])) {
            return $this->error('商品参数有误!');
        }

        if ($data['mall_id']) {
            $proInfo = target('mall/MallProducts')->getWhereInfo(['A.mall_id' => $data['mall_id']]);
        } else {
            $proInfo = target('mall/MallProducts')->getMallInfo($data['pro_id']);
        }

        if (empty($proInfo) || !$proInfo['status']) {
            return $this->error('该商品不存在!');
        }
        if ($proInfo['up_time']) {
            if ($proInfo['up_time'] > time()) {
                return $this->error('该商品还未上架!');
            }
        }
        if ($proInfo['down_time']) {
            if ($proInfo['down_time'] < time()) {
                return $this->error('该商品已下架!');
            }
        }
        if (empty($proInfo['store'])) {
            return $this->error('该商品库存不足！');
        }

        if ($proInfo['store'] < $data['qty']) {
            return $this->error('该商品库存不足!');
        }

        $info = target('mall/Mall')->getInfo($proInfo['mall_id']);

        $cartData = [];

        $cartData['item_no'] = $proInfo['products_no'];
        $cartData['app'] = 'mall';
        $cartData['app_id'] = $proInfo['mall_id'];
        $cartData['id'] = $proInfo['products_id'];
        $cartData['qty'] = $qty;
        $cartData['price'] = $proInfo['sell_price'];
        $cartData['name'] = $proInfo['title'];
        $cartData['options'] = $proInfo['spec_data'];
        $cartData['image'] = $proInfo['image'];
        $cartData['weight'] = $proInfo['weight'];
        $cartData['url'] = url('controller/mall/info/index', ['id' => $proInfo['mall_id']]);
        $cartData['freight_type'] = $proInfo['freight_type'];
        $cartData['freight_tpl'] = $proInfo['freight_tpl'];
        $cartData['freight_price'] = $proInfo['freight_price'];
        $cartData['service_status'] = $proInfo['service_status'];
        $cartData['cod_status'] = $proInfo['cod_status'];
        $cartData['seller_id'] = $proInfo['seller_id'];
        $cartData['point'] = 0;
        $cartData['extend'] = [
            'chb_status' => $info['chb_status'],
        ];

        $config = target('shop/ShopConfig')->getConfig();
        if ($config['point_status'] && $proInfo['point_status']) {
            $cartData['point'] = round($proInfo['sell_price'] * $config['point_rate'] / 100);
        }

        if (!target('order/Cart', 'service')->add($userId, $cartData)) {
            return $this->error(target('order/Cart', 'service')->getError());
        }

        return $this->success();
    }

    /**
     * 刷新购物车
     * @param $userId
     * @param $info
     * @return bool
     */
    public function refreshCart($userId, $info) {
        if (empty($info)) {
            return $this->success();
        }

        $ids = [];
        foreach ($info['items'] as $key => $vo) {
            $ids[] = $vo['id'];
        }
        $where = [];
        $where['_sql'] = 'products_id in (' . implode(',', $ids) . ')';
        $proList = target('mall/MallProducts')->loadList($where);

        $proData = [];
        foreach ($proList as $vo) {
            $proData[$vo['products_id']] = $vo;
        }
        $storeError = 0;
        $priceError = 0;
        $emptyErrpr = 0;
        $cartData = [];

        foreach ($info['items'] as $key => $vo) {

            if (empty($proData[$vo['id']])) {
                $emptyErrpr = 1;
                target('order/Cart', 'service')->del($userId, $vo['rowid']);
                continue;
            }

            $cart = [];
            if ($vo['qty'] > $proData[$vo['id']]['store']) {
                $storeError = 1;
                $cart['qty'] = 1;
            }
            if ($vo['price'] <> $proData[$vo['id']]['sell_price']) {
                $priceError = 1;
                $cart['price'] = $proData[$vo['id']]['sell_price'];
            }
            if ($cart) {
                $cart['rowid'] = $vo['rowid'];
                $cartData[] = $cart;
            }
        }

        if ($emptyErrpr) {
            return $this->error('您购买的产品已被删除，请重新提交!');
        }

        if (!empty($cartData)) {
            if (!target('order/Cart', 'service')->update($userId, $cartData)) {
                return $this->error(target('order/Cart', 'service')->getError());
            }
            if ($storeError && $priceError) {
                return $this->error('您购买的产品由于库存和价格更改,请重新提交订单!');
            }
            if ($storeError) {
                return $this->error('您购买的产品由于库存不足,请重新提交订单!');
            }
            if ($priceError) {
                return $this->error('您购买的产品由于价格更改,请重新提交订单!');
            }
        }

        return $this->success();
    }

    /**
     * 提交订单
     * @param array $data
     * @param array $goodsData
     * @return bool
     */
    public function addOrder($data = [], $goodsData = []) {
        if (empty($data) || empty($goodsData)) {
            return $this->error('订单数据为空!');
        }
        $id = target($this->model)->add([
            'order_id' => $data['order_id']
        ]);
        if (!$id) {
            return $this->error(target($this->model)->getError());
        }

        $config = target('shop/ShopConfig')->getConfig();
        if (!$config['stock_type']) {
            if (!$this->saleOrder($goodsData)) {
                return false;
            }
        }

        return $this->success($id);
    }

    /**
     * 支付订单检查
     * @param $orderList
     * @return bool
     */
    public function checkOrder($orderList) {
        return true;
    }

    /**
     * 付款成功回调
     * @param $goodsData
     * @return bool
     */
    public function payOrder($goodsData) {
        $config = target('shop/ShopConfig')->getConfig();
        if ($config['stock_type']) {
            if (!$this->saleOrder($goodsData)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 取消订单操作
     * @param $orderList
     * @return bool
     */
    public function cancelOrder($orderList) {
        return true;
    }

    /**
     * 订单发货
     * @param $orderInfo
     * @return bool
     */
    public function deliveryOrder($orderInfo) {
        return true;
    }

    /**
     * 订单完成
     * @param $orderInfo
     * @return bool
     */
    public function confirmOrder($orderInfo) {
        $orderGoods = target('order/OrderGoods')->loadList([
            'order_id' => $orderInfo['order_id']
        ]);
        $currencyList = target('member/Currency', 'service')->getAllCurrency();
        $currency = $orderInfo['order_currency'];

        $profitsRate = target('merchant/Merchant', 'service')->profitsRate($orderInfo['order_seller_id']);

        $chbConfig = target('chb/ChbConfig')->getConfig();

        if(!$profitsRate) {
            return true;
        }


        foreach ($currency as $key => $vo) {
            if($key <> 'chb') {
                continue;
            }
            if($vo['pay_status']) {
                continue;
            }
            //计算惠币
            $money = 0;
            foreach ($orderGoods as $goods) {
                $extend = $goods['extend'];
                if(!$extend['chb_status']) {
                    continue;
                }
                $money += $goods['price_total'];
            }

            if(empty($money)) {
                return true;
            }

            //返还惠币
            $money = round($money * $profitsRate / 100, 2);
            $money = round($money * $chbConfig['return_rate'] / 100, 2);
            $money = $money*$chbConfig['exchange_rate'];

            if(!target($currencyList[$key]['target'], 'service')->payAmountCurrency($key, $orderInfo['order_user_id'], $money, '', '系统返利', '订单完成返还惠币', 1)) {
                return $this->error(target($currencyList[$key]['target'], 'service')->getError());
            }

        }

        return true;
    }

    /**
     * 库存处理
     * @param $goodsData
     * @return bool
     */
    public function saleOrder($goodsData) {
        if (empty($goodsData)) {
            return true;
        }
        $data = [];
        foreach ($goodsData as $vo) {
            $data[$vo['has_id']][] = $vo;
        }

        foreach ($data as $hasId => $goods) {
            $qty = 0;
            foreach ($goods as $vo) {
                $qty += $vo['goods_qty'];
                if (!target('mall/MallProducts')->where(['products_id' => $vo['sub_id']])->setDec('store', $vo['goods_qty'])) {
                    return $this->error('库存处理失败！');
                }
                if (!target('mall/MallProducts')->where(['products_id' => $vo['sub_id']])->setInc('sale', $vo['goods_qty'])) {
                    return $this->error('销量处理失败！');
                }
            }
            if (!target('mall/Mall')->where(['mall_id' => $hasId])->setDec('store', $qty)) {
                return $this->error('库存处理失败！');
            }
            if (!target('mall/Mall')->where(['mall_id' => $hasId])->setInc('sale', $qty)) {
                return $this->error('销量处理失败！');
            }

        };

        return true;

    }
}

